<?php

require FCPATH . '/application/controllers/backend/backend.php';

class Job extends Backend {

    public function __construct() {
	parent::__construct();
	$this->load->model('job_model', 'model');
    }

    public function index() {
	$this->load_javascripts('backend_job_index');
	$this->rend('job_index_view');
    }

    public function records() {
	$page = intval($this->input->get('page'));
	$page_size = intval($this->input->get('pageSize'));
	$page = $page ? $page : 1;
	$page_size = $page_size ? $page_size : 10;
	$offset = $page_size * ($page - 1);
	$this->json_back('XT001', '', array(
	    'total' => $this->model->total(),
	    'records' => $this->model->records($page_size, $offset)
	));
    }

    public function find() {
	$id = intval($this->input->get('id'));
	if (!($data = $this->model->find($id))) {
	    $this->json_back('XT002', '该记录已被删除,或ID有误。');
	}
	$this->json_back('XT001', '', $data);
    }

    public function insert() {
	$data = array(
	    'position' => trim($this->input->post('position')),
	    'requirements' => trim($this->input->post('requirements')),
	    'position_en' => trim($this->input->post('position_en')),
	    'requirements_en' => trim($this->input->post('requirements_en')),
	    'created_at' => date('Y-m-d H:i:s')
	);

	$max_order = $this->model->max_order();
	$data['order'] = intval($max_order) + 1;

	if (($id = $this->model->insert($data)) > 0) {
	    $this->json_back('XT001', '', array('id' => $id));
	}

	$this->json_back('XT002', '数据库或SQL语句有误。');
    }

    public function update() {
	$id = intval($this->input->post('id'));
	$data = array(
	    'position' => trim($this->input->post('position')),
	    'requirements' => trim($this->input->post('requirements')),
	    'position_en' => trim($this->input->post('position_en')),
	    'requirements_en' => trim($this->input->post('requirements_en'))
	);
	if ($this->model->update($id, $data)) {
	    $this->json_back('XT001', '', array('id' => $id));
	}
	$this->json_back('XT002', '数据库或SQL语句有误。');
    }

    public function delete() {
	$id = $this->input->get('id');
	if ($this->model->delete($id)) {
	    $this->json_back('XT001', '删除成功。');
	}
	$this->json_back('XT002', '数据库或SQL语句有误。');
    }

    public function order() {
	$id = intval($this->input->post('id'));
	$order = intval($this->input->post('order'));

	$max_order = $this->model->max_order();

	if ($order > ($max_order + 1)) {
	    //$this->json_back('XT002',"请输入1到{$max_order}之间的一个数。");
	}

	if ($this->model->order($id, $order)) {
	    $this->json_back('XT001', '排序成功');
	} else {
	    $this->json_back('XT002', '数据库错误');
	}
    }

}
